/********************************************************************************
 * Project Name		[JavaSE_Fundamentals]
 * File Name     	[MoneyTransfer.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package thread.synchronization;

/**
 * 转账程序
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class MoneyTransfer implements Runnable {

	private final Bank bank;
	private final int fromAccount;
	private final double maxAmount;
	private static final long DELAY = 10;

	/**
	 * 转账
	 * 
	 * @param bank
	 * @param fromAccount
	 * @param maxAmount
	 */
	public MoneyTransfer(Bank bank, int fromAccount, double maxAmount) {
		this.bank = bank;
		this.fromAccount = fromAccount;
		this.maxAmount = maxAmount;
	}

	@Override
	public void run() {
		try {
			while (true) {
				int toAccount = (int) (bank.getAccountNumber() * Math.random());
				double amount = maxAmount * Math.random();
				bank.transfer(fromAccount, toAccount, amount);
				Thread.sleep((int) (DELAY * Math.random()));
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
